package cn.tq365.service.baidu;

import javax.annotation.Resource;

import org.apache.ibatis.executor.BatchExecutor;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import cn.tq365.util.baidu.SyncServiceFactory;
import cn.tq365.util.mybatis.SqlSessionFactoryUtil;

import com.baidu.api.client.core.ClientBusinessException;
import com.baidu.api.client.core.ResHeaderUtil;
import com.baidu.api.client.core.VersionService;
import com.baidu.api.sem.common.v2.ResHeader;
import com.baidu.api.sem.sms.v2.AccountService;
import com.baidu.api.sem.sms.v2.GetAccountInfoRequest;
import com.baidu.api.sem.sms.v2.GetAccountInfoResponse;

@Service
@Scope("prototype")
public class TempService {
	@Resource
	SqlSessionFactoryUtil sqlSessionFactoryUtil;

	/**
	 * 添加
	 * 
	 * @param account
	 * @throws Exception
	 */
	public void batchAdd(String userName, String password) throws Exception {
		SqlSession session = null;
		BatchExecutor be = null;
		try {
			VersionService factory = SyncServiceFactory.getInstance(userName,
					password);
			AccountService service = factory.getService(AccountService.class);
			GetAccountInfoRequest parameters = new GetAccountInfoRequest();
			parameters.setType(1);
			GetAccountInfoResponse ret = service.getAccountInfo(parameters);
			ResHeader rheader = ResHeaderUtil.getResHeader(service, true);

			SqlSessionFactory sqlSessionFactory = sqlSessionFactoryUtil
					.getSqlSessionFactory();

			if (rheader.getStatus() == 0) {
				session = sqlSessionFactory.openSession(ExecutorType.BATCH,
						false);
				long bt = System.currentTimeMillis();
				for (int i = 0; i < 100; i++) {
					session.insert(
							"cn.tq365.mapper.SyncBaiduAccountMapper.add",
							ret.getAccountInfoType());
				}
				System.out.println(System.currentTimeMillis() - bt);
				// int j = 1 / 0;
				session.commit();
			} else {
				throw new ClientBusinessException(rheader, ret);
			}
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
}